package com.gla.Controller;

import com.gla.domain.User;
import com.gla.domain.UserVO;
import com.gla.result.Result;
import com.gla.service.LoginService;
import com.gla.util.JwtUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/login")
public class LoginController {
    @Resource
    LoginService loginService;

    @GetMapping("/login")
    public Result user(@RequestParam String account, @RequestParam String password) {
        //校验账号密码
        User getUser =  loginService.select(account, password);
        if(getUser != null) {
            UserVO vo = new UserVO(getUser);
            vo.setToken(JwtUtil.generateToken(getUser.getId()));//生成和设置token
            return Result.succeed(vo);
        }
        return Result.fail("账号或密码错误！");
    }
    @PostMapping("/register")
    public Result register(User user){
        List<User> list =  loginService.check(user.getAccount());
        if(list.size()==0){
            user.setIs_vip(0);
            loginService.register(user);
            return Result.succeed("注册成功");
        }
        else{
            return Result.succeed("该账号已存在");
        }
    }
    @GetMapping("/checkName")
    public Result check(@RequestParam String username){
        List<User> list =  loginService.check(username);
        return Result.succeed(list.size());
    }
}
